package com.zch.rpc.core.net.jetty1;


import com.zch.rpc.core.model.RpcRequestModel;
import com.zch.rpc.core.model.RpcResponseModel;
import com.zch.rpc.core.provider.RpcProviderFactory;
import com.zch.rpc.core.serialize.impl.HessianSerializer;
import com.zch.rpc.core.util.HttpClientUtil;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * jetty handler
 */
public class JettyServerHandler extends AbstractHandler {
	private static Logger logger = LoggerFactory.getLogger(JettyServerHandler.class);
	HessianSerializer hessianSerializer=new HessianSerializer();

	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		// invoke
        RpcResponseModel rpcResponse = doInvoke(request);

        // serialize response
        byte[] responseBytes = hessianSerializer.serialize(rpcResponse);
		
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		baseRequest.setHandled(true);
		
		OutputStream out = response.getOutputStream();
		out.write(responseBytes);
		out.flush();
		
	}

	private RpcResponseModel doInvoke(HttpServletRequest request) {
		try {
			// deserialize request
			byte[] requestBytes = HttpClientUtil.readBytes(request);
			if (requestBytes == null || requestBytes.length==0) {
				RpcResponseModel rpcResponse = new RpcResponseModel();
				rpcResponse.setErrorMsg("RpcRequest byte[] is null");
				return rpcResponse;
			}
			RpcRequestModel rpcRequest = (RpcRequestModel) hessianSerializer.deserialize(requestBytes, RpcRequestModel.class);

			// invoke
			RpcResponseModel responseModel= RpcProviderFactory.invokerService(rpcRequest);
			return responseModel;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);

			RpcResponseModel rpcResponse = new RpcResponseModel();
			rpcResponse.setErrorMsg("Server-error:" + e.getMessage());
			return rpcResponse;
		}
	}

}
